package com.jungle.app.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jungle.base.my.config.properties.WeChatProperties;
import com.jungle.app.domain.bo.UserAccountLoginDTO;
import com.jungle.app.domain.bo.UserLoginDTO;
import com.jungle.app.repository.UserLoginRepository;
import com.jungle.app.service.UserLoginService;
import com.jungle.common.constant.MessageConstant;
import com.jungle.common.core.domain.entity.MyUser;
import com.jungle.common.exception.app.AccountLockedException;
import com.jungle.common.exception.app.AccountNotFoundException;
import com.jungle.common.exception.app.LoginFailedException;
import com.jungle.common.exception.app.PasswordErrorException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {

    private final UserLoginRepository repository;

    @Override
    public MyUser register(UserAccountLoginDTO loginDTO) {
        String phoneNumber = loginDTO.getPhoneNumber();
        String password = loginDTO.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        MyUser user = new MyUser();
        user.setPhoneNumber(phoneNumber);
        user.setPassword(password);
        user.setConcernNum(0);
        user.setFanNum(0);
        MyUser saved = repository.save(user);
        log.info("新增用户：{}", saved);
        return saved;
    }

    @Override
    public MyUser login(UserAccountLoginDTO loginDTO) {
        String phoneNumber = loginDTO.getPhoneNumber();
        String password = loginDTO.getPassword();
        //根据手机号去查用户
        MyUser havaUser = repository.findByPhoneNumber(phoneNumber);
        if (havaUser == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //MD5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!havaUser.getPassword().equals(password)) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        if (havaUser.getStatus() == 0) {
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        return havaUser;
    }

    /**
     * 微信登录
     *
     * @param loginDTO
     */
    @Override
    public MyUser wxLogin(UserLoginDTO loginDTO) {
        String openid = getOpenid(loginDTO.getCode());//获取openid
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        MyUser user = repository.findByOpenid(openid);
        //第一次登录，自动注册
        if (user == null) {
            user = new MyUser();
            BeanUtils.copyProperties(loginDTO, user);
            user.setOpenid(openid);
            user.setConcernNum(0);
            user.setFanNum(0);
            //设置默认昵称
            long count = repository.countByWx() + 1;
            user.setNickName("微信用户" + count);
            //设置微信新用户默认头像
            user.setAvatar("http://172.20.5.108:9000/smart-bucket/0ab4fc7b63a7429483a6d602402135d3.png");
            MyUser saved = repository.save(user);

            log.info("新增微信登录用户：{}", saved);
        }
//        else {//更新已登录的用户信息
//            BeanUtils.copyProperties(loginDTO, user);
//            User saved = repository.save(user);
//            log.info("更新已登录的用户信息：{}", saved);
//        }
        return user;
    }

    private final WeChatProperties weChatProperties;
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 根据code调用微信登录的授权登录接口获取openid
     *
     * @param code 用户微信授权后返回的code
     * @return
     */
    private String getOpenid(String code) {

        HashMap<String, Object> map = new HashMap<>() {{
            put("appid", weChatProperties.getAppid());
            put("secret", weChatProperties.getAppsecret());
            put("js_code", code);
            put("grant_type", "authorization_code");
        }};
        String jsonBackMsg = HttpUtil.get(WX_LOGIN, map);
        JSONObject jsonObject = JSONUtil.parseObj(jsonBackMsg);

        return (String) jsonObject.get("openid");
    }
}
